package com.jstyle.jclifexd.fragment;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.google.android.flexbox.FlexboxLayoutManager;
import com.jstyle.jclifexd.NetWork.NetWorkUtil;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.adapter.HeartDetailAdapter;
import com.jstyle.jclifexd.adapter.HistoryShowAdapter;
import com.jstyle.jclifexd.daoManager.HeartDataDaoManager;
import com.jstyle.jclifexd.daoManager.UserInfoDaoManager;
import com.jstyle.jclifexd.model.HeartData;
import com.jstyle.jclifexd.model.UserInfo;
import com.jstyle.jclifexd.utils.ChartDataUtil;
import com.jstyle.jclifexd.utils.DateUtil;
import com.jstyle.jclifexd.utils.ResolveData;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import lecho.lib.hellocharts.view.LineChartView;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link HeartHistoryYearFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HeartHistoryYearFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.bt_sleep_week_pre)
    ImageView btSleepWeekPre;
    @BindView(R.id.bt_sleep_week_date)
    Button btSleepWeekDate;
    @BindView(R.id.bt_sleep_week_next)
    ImageView btSleepWeekNext;
    @BindView(R.id.LineChartView_heart_week)
    LineChartView LineChartViewHeartWeek;
    @BindView(R.id.RecyclerView_heart_total)
    RecyclerView RecyclerViewHeartTotal;
    @BindView(R.id.bt_thisWeek)
    Button btThisWeek;
    @BindView(R.id.RecyclerView_heartWeek)
    RecyclerView RecyclerViewHeartWeek;
    Unbinder unbinder;
    @BindView(R.id.tv_noData)
    Button tvNoData;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private boolean isBusy;
    private static final String TAG = "HeartHistoryWeekFragmen";
    private HashMap<Integer, Integer> maxHrMap = new HashMap<>();
    private HashMap<Integer, Integer> staticHrMap = new HashMap<>();
    private HashMap<Integer, Integer> avgHrMap = new HashMap<>();
    private List<String> listContent;
    private HistoryShowAdapter historyShowAdapter;
    private String thisMonth;
    private String[] monthDates;
    private int year;
    private int MHR;
    int[] heartRange;
    int[] lastWeekHeartRange;

    public HeartHistoryYearFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HeartHistoryWeekFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HeartHistoryYearFragment newInstance(String param1, String param2) {
        HeartHistoryYearFragment fragment = new HeartHistoryYearFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_heart_history_week, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        getMaxHr();

        year = Calendar.getInstance().get(Calendar.YEAR);
        //   thisMonth = DateUtil.getMonthString("", DateUtil.this_month);
        monthDates = DateUtil.getThisMonth();

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewHeartWeek.setLayoutManager(linearLayoutManager);
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        ColorDrawable colorDrawable = new ColorDrawable();
        colorDrawable.setColor(Color.DKGRAY);
        dividerItemDecoration.setDrawable(colorDrawable);
        RecyclerViewHeartWeek.addItemDecoration(dividerItemDecoration);
        FlexboxLayoutManager layoutManager2 = new FlexboxLayoutManager(getActivity());
        listContent = new ArrayList<>();
        listContent.add(getString(R.string.Minimum_HR));
        listContent.add(getString(R.string.Maximum_HR));
        historyShowAdapter = new HistoryShowAdapter(listContent);
        RecyclerViewHeartTotal.setAdapter(historyShowAdapter);
        RecyclerViewHeartTotal.setLayoutManager(layoutManager2);
        findData();
    }

    private void getMaxHr() {
        String account = NetWorkUtil.getUserId();
        UserInfo userInfo = UserInfoDaoManager.getUserByUid(account);
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setUserId(account);
            UserInfoDaoManager.insertUser(userInfo);
        }
        String birthday = userInfo.getBirthday();
        int userYear = Integer.parseInt(birthday.split("-")[0]);
        Calendar calendar = Calendar.getInstance();
        int age = calendar.get(Calendar.YEAR) - userYear;
        MHR = 220 - age;
    }

    private void findData() {
        String showDate = String.valueOf(year);
        btSleepWeekDate.setText(showDate);
        Calendar calendar = Calendar.getInstance();
        int thisYear = calendar.get(Calendar.YEAR);
        btSleepWeekNext.setEnabled(year != thisYear);
        isBusy = true;
        maxHrMap.clear();
        staticHrMap.clear();
        avgHrMap.clear();
        String startDate = showDate.substring(2, 4) + ".01.01";
        String endDate = showDate.substring(2, 4) + ".12.31";
        heartRange = new int[5];
        lastWeekHeartRange = new int[5];
        String lastDate = String.valueOf(year - 1);
        String lastStartDate = lastDate.substring(2, 4) + ".01.01";
        String lastEndDate = lastDate.substring(2, 4) + ".12.31";
        mergeHeartData(startDate, endDate, lastStartDate, lastEndDate);
    }

    private Observable<Integer> getThisYearHeartData(final String startDate, final String endDate) {
        return Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                List<HeartData> heartDataList = HeartDataDaoManager.queryYearData(startDate, endDate);
                getHeartRate(heartDataList, startDate);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.newThread());
    }

    private Observable<Integer> getLastYearHeartData(final String startDate, final String endDate) {
        return Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> e) throws Exception {
                List<HeartData> heartDataList = HeartDataDaoManager.queryYearData(startDate, endDate);
                getLastYearHeartRate(heartDataList, startDate);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.newThread());
    }

    private void mergeHeartData(final String startDate, final String endDate, final String lastStartDate, final String laseEndDate) {
        showLoadingDialog();
        List<Observable<Integer>> observables = new ArrayList<>();
        observables.add(getThisYearHeartData(startDate, endDate));
        observables.add(getLastYearHeartData(lastStartDate, laseEndDate));
        Observable.merge(observables).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Integer value) {
                Log.i(TAG, "onNext: " + value);
            }

            @Override
            public void onError(Throwable e) {
                disMissLoadingDialog();
                isBusy = false;
                Log.i(TAG, "onError: " + e.getMessage());
            }

            @Override
            public void onComplete() {
                disMissLoadingDialog();
                //setRecycleViewData();
                setDayRecycleViewData();
                setHeartChartViewData();
                isBusy = false;
            }
        });
    }


    private void setDayRecycleViewData() {
        HeartDetailAdapter heartDetailAdapter = new HeartDetailAdapter(heartRange, lastWeekHeartRange, HeartDetailAdapter.DATA_YEAR);
        RecyclerViewHeartWeek.setAdapter(heartDetailAdapter);

    }

    private void setHeartChartViewData() {
        if(avgHrMap.size()!=0){
            tvNoData.setVisibility(View.GONE);
            LineChartViewHeartWeek.setVisibility(View.VISIBLE);
        }else{
            tvNoData.setVisibility(View.VISIBLE);
            LineChartViewHeartWeek.setVisibility(View.GONE);
        }
      int max = 0;
        for (Map.Entry<Integer, Integer> entry : maxHrMap.entrySet()) {
            max = Math.max(max, entry.getValue());
        }
        int totalStatic = 0;
        int count = 0;
        for (Map.Entry<Integer, Integer> entry : staticHrMap.entrySet()) {
            int hr = entry.getValue();
            if (hr != 0) {
                totalStatic += hr;
                count++;
            }
        }
        int avgHr = count == 0 ? 0 : totalStatic / count;
        List<String> listHeart = new ArrayList<>();//总计列表
        String label=" "+getResources().getString(R.string.hr_laber);

        listHeart.add(avgHr + label);
        listHeart.add(max + label);
        historyShowAdapter.setStepData(listHeart);
        float top=0;
        if(max%10==0){
            top=max;
        }else{
            top=(((int)max/10)+1)*10;
        }
        ChartDataUtil.initDataChartView(LineChartViewHeartWeek, -0.5f, top+10, 12, 40);
        LineChartViewHeartWeek.setLineChartData(ChartDataUtil.getYearHeartHistoryChart(getActivity(), avgHrMap,top));

    }


    private void getHeartRate(List<HeartData> heartDataList, String date) {
        int maxHr = 0;
        int staticHr = 300;
        HashMap<Integer, List<Integer>> yearValue = new HashMap<>();
        for (HeartData data : heartDataList) {
            String time = data.getTime();
            int month = Integer.parseInt(time.substring(3, 5));
            int value = data.getHeart();
            Integer maxValue = maxHrMap.get(month);
            Integer staticValue = staticHrMap.get(month);
            List<Integer> list = yearValue.get(month);
            if (value != 0) {
                int range=ResolveData.getHeartRange(value, MHR);
                if(range!=-1)heartRange[range]++;
                if (list == null) list = new ArrayList<>();
                list.add(value);
                yearValue.put(month, list);
                maxHrMap.put(month, maxValue == null ? value : Math.max(maxValue, value));
                staticHrMap.put(month, maxValue == null ? value : Math.min(staticValue, value));
            }
        }
        for (Map.Entry<Integer, List<Integer>> entry : yearValue.entrySet()) {
            List<Integer> list = entry.getValue();
            int month = entry.getKey();
            float totalHR = 0;
            float count = 0;
            for (Integer value : list) {
                totalHR += value;
                count++;
            }
            avgHrMap.put(month, count == 0 ? 0 : (int) (totalHR / count));
        }
    }

    private void getLastYearHeartRate(List<HeartData> heartDataList, String date) {
        for (HeartData data : heartDataList) {
            int value = data.getHeart();
            if (value != 0) {
                int range=ResolveData.getHeartRange(value, MHR);
                if(range!=-1)lastWeekHeartRange[range]++;

            }
        }

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.bt_sleep_week_pre, R.id.bt_sleep_week_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_sleep_week_next:
                year++;
                monthDates = DateUtil.getNextMonth(monthDates[0]);
                findData();
                break;
            case R.id.bt_sleep_week_pre:
                year--;
                monthDates = DateUtil.getLastMonth(monthDates[0]);
                findData();
                break;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
